﻿using BasicData.API.Read.Application.Commands;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infrastructure.interfaces;
using MediatR;

namespace BasicData.API.Read.Application.CommandHandlers
{
    public class GetGoodsCommandHandler : IRequestHandler<GetGoodsCommand, APIResult<APIPaging<GoodsModel>>>
    {
        private readonly IBaseRepository<GoodsModel> baseRepository;

        public GetGoodsCommandHandler(IBaseRepository<GoodsModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public async Task<APIResult<APIPaging<GoodsModel>>> Handle(GetGoodsCommand request, CancellationToken cancellationToken)
        {
            var list=baseRepository.GetAll();
            if(request.GoodsTitle!=null)
            {
                list = list.Where(x => x.GoodsTitle == request.GoodsTitle);
            }
            if (request.GoodsCode != null)
            {
                list = list.Where(x => x.GoodsCode == request.GoodsCode);
            }
            int totalCount=list.Count();
            list = list.OrderByDescending(x => x.GoodsId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<GoodsModel> paging = new APIPaging<GoodsModel>()
            {
                PageCount = list.ToList(),
                TotalCount = totalCount,
            };
            return APIResult<APIPaging<GoodsModel>>.Success("显示成功",paging);
        }
    }
}
